//index.js
//获取应用实例
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js')
import tool from '../tool/tool'
Page({
	data: {
		isLoad: true,
		noMore: false, //没有更多啦
		getGoodsList: 0, //是否赋值
		
		navList: [{
				'title': '首页',
				'img': '../../images/home.png',
				'selectImg': '../../images/homeSelect.png',
				'select': true,
				'navTitle': '聚惠口袋'
			},
			{
				'title': '我的',
				'img': '../../images/myself.png',
				'selectImg': '../../images/myselfSelect.png',
				'select': false,
				'navTitle': '我的'
			}
		],
		Hb: false,
		myself: [{
			img: '../../images/payment.png',
			text: '待付款'
		}, {
			img: '../../images/take.png',
			text: '待收货'
		}, {
			img: '../../images/finish.png',
			text: '已完成'
		}],
		problem: [{
				'text': '收货地址',
				"img": '../../images/address.png',
			},
			{
				'text': '联系我们',
				"img": '../../images/wechat.png',
				'type': 'contact'
			},
			{
				'text': '我要投诉',
				"img": '../../images/complaint.png'
			}
		],
		imgWidth: '', //图片高度
		tabArr: {
			curHdIndex: 1,
			curBdIndex: 1
		},
		page: 1,
		goods_data: [],
		red_packet:'',
		options:'',
		userCenterList:['我的订单','我的优惠券','收货地址','个人设置','联系我们','我要投诉']
	},

	onLoad: function(options) {
		console.log(this.data);
		var that = this
		console.log(321,options)
		that.setData({
			imgWidth: wx.getSystemInfoSync().screenWidth - 55,
			width: wx.getSystemInfoSync().screenWidth,
			isIphoneX: app.globalData.isIphoneX,
			red_id: options.red_id || '',
			options:options
		})
		if (options.jump) {
			wx.navigateTo({
				url: `${options.jump}?gid=${options.gid}`,
			})
		}
		if (options.scene) {
			if (options.scene.length) {
				if (options.scene[0] == 'r') {
					that.setData({
						red_id: options.scene.substring(1, options.scene.length)
					})
				}
			}
		}
	},
	onShow: function() {
		let that = this
		// that.data.goods_data = []
		// that.data.getGoodsList = 0
		let tabArr = wx.getStorageSync('nav') ? wx.getStorageSync('nav') : {
			curBdIndex: 1,
			curHdIndex: 1
		}
		that.setData({
			tabArr: tabArr
		})
		console.log(that.data.tabArr.curHdIndex,9651)
		if (!app.globalData.loginStatus) {
			//使用es6的promise进行异步处理
			let promise = new Promise(function(resolve, reject) {
				util.getLogin(resolve)
			});
			promise.then(function() {
				that.getGoodList(1, that.data.tabArr.curHdIndex, that.data.red_id)
			})
		} else {
			that.getGoodList(1, that.data.tabArr.curHdIndex, that.data.red_id)
		}
	},
	tabFun: function(e) {
		//获取触发事件组件的dataset属性
		var that = this
		var _datasetId = e.target.dataset.id;
		var _obj = {};
		if (_datasetId != that.data.tabArr.curHdIndex) {
			that.data.getGoodsList = 0
			_obj.curHdIndex = _datasetId;
			_obj.curBdIndex = _datasetId;
			that.setData({
				tabArr: _obj,
				goods_data: [],
				isLoading: true
			})
			wx.setStorageSync('nav', _obj)
			that.getGoodList(1, Number(_datasetId))
		}
	},
	//底部导航栏切换
	navBtn: function(e) {
	
		
		var that = this
		let navList = that.data.navList,
			index = e.currentTarget.dataset.index
			console.log(navList[index].title=="我的");
			
					if(navList[index].title=="我的"&&app.globalData.wxshouquan==false){
				
					that.getUserProfile()
				
				
						
			}
		
		
		wx.setNavigationBarTitle({
			title: navList[index].navTitle,
		})
		for (let i in navList) {
			console.log(i);
			if (i == index) {
				navList[i].select = true
			} else {
				navList[i].select = false
			}
		}
		console.log(index)
		
	
		wx.setNavigationBarColor({
			frontColor: index == 0 ? '#000000':'#ffffff',
			backgroundColor: index == 0 ? '#ffffff':'#edc69b',
			animation: {
				duration:0,
				timingFunc: 'easeIn'
			}
		})
		that.setData({
			navList: navList,
			userInfo: app.globalData.userInfo,
		})
	
		
	},
	//拉取首页列表
	getGoodList: function(page, tag_id, red_id) {
		let that = this
		let data = {
			page: page,
			limit: 10,
			mid: 1,
			tag_id: tag_id
		}
		if (that.data.options.red_id) {
			data.red_id = that.data.options.red_id
		}
		let goodsListPromise = new Promise(function(resolve, reject) {

			api.goodsList({
				data: data,
				success: res => {
					let goods_data = that.data.goods_data
					if (that.data.goods_data.length != 0) {
						goods_data = goods_data.concat(res.data.result.data.goods_data)
					} else {
						goods_data = res.data.result.data.goods_data
					}
					app.globalData.kefu_wx = res.data.result.data.system_info.kefu_wx
					if (res.data.result.data.use_end_time) {
						that.setData({
							end_time: res.data.result.data.use_end_time
						})
					}
					console.log(46,app.globalData.authStatus)
					that.setData({
						authStatus: app.globalData.authStatus,
						isLoading: false,
						tag_list: res.data.result.data.tag_list,
						bannerUrls: res.data.result.data.system_info.index_banner,
						goods_data: that.data.getGoodsList == 0 ? goods_data : that.data.goods_data,
						next: that.data.getGoodsList == 0 ? res.data.result.next : that.data.next,
						page: page,
						isLoad: false,
						money: res.data.result.data.money ? res.data.result.data.money : 0,
						red_packet: res.data.result.data.red_packet.money ? res.data.result.data.red_packet:'',
						Hb: res.data.result.data.red_packet.id ? true : false,
						can_use: res.data.result.data.can_use ? true : false,
						is_get: res.data.result.data.is_get,
						red_status: res.data.result.data.red_status,
						noMore: res.data.result.next === 0 ? true : false,
						getGoodsList: Number(that.data.getGoodsList) + 1,
						// userInfo: res.data.result.data.user_info,
						userInfo: app.globalData.userInfo,
					})
					
					// if(that.data.red_packet && that.data.red_packet.path){
					// 	options.gid
					// }
					// console.log(res)
					if (res.data.result.data.red_packet_name) {
						that.setData({
							red_packet_name: res.data.result.data.red_packet_name
						})
					}
					if (res.data.result.data.red_status == 2) {
						// util.showToast('红包已过期~', 'none')
						that.setData({
							red_id: '',
							['options.all']:false
						})
					}
					resolve()
				},
				fail: res => {
					reject(res)
				}
			})
		})
		goodsListPromise.then(function() {
			if (that.data.end_time) {
				that.countTime()
			}
		}).catch(err => {
			console.log(777,err)
		})
	},
	
	//我的页面 栏目点击事件
	liClick: function(e) {
		let index = e.currentTarget.dataset.id;
		var app=getApp()
		
		switch (Number(index)) {
			case 0://我的订单

			if(app.globalData.wxshouquan==false){
				this.getUserProfile()
			
			}else{
				wx.navigateTo({//查看全部订单
					url: '../myOrder/myOrder',
				})
			}
				
		        break;
			case 1://我的优惠券
			if(app.globalData.wxshouquan==false){
				this.getUserProfile()
			}else{
				wx.navigateTo({
					url: '../myRedPacket/myRedPacket',
				})
			}
				
		        break;
			case 2://收货地址
			if(app.globalData.wxshouquan==false){
				this.getUserProfile()
			}else{
				this.openItem(index)
			}
				
		        break;
			case 3://个人设置
			if(app.globalData.wxshouquan==false){
				this.getUserProfile()
			}
		        break;
			case 4://联系我们
			if(app.globalData.wxshouquan==false){
				this.getUserProfile()
			}
		        break;
			case 5://我要投诉
			if(app.globalData.wxshouquan==false){
				this.getUserProfile()
			
			}else{
					wx.navigateTo({
					url: '../complaint/complaint',
				})
			}
				break;
		}
	},
	
	//点击栏目按钮
	openItem: function(index) {
		let that = this

		if (index == 2) {
			var nowTime = new Date();
			if (nowTime - that.data.payTime < 1000) {
				return;
			}
			that.setData({
				'payTime': nowTime
			});
			wx.getSetting({
				success(res) {
					if (!(JSON.stringify(res.authSetting) == '{}')) {
						if (res.authSetting['scope.address']) {
							// 获取地址
							wx.chooseAddress({})
						} else if (res.authSetting['scope.address'] == false) {
							that.setData({
								isAddress: true
							});
						} else {
							wx.chooseAddress({

							})
						}
					} else {
						wx.chooseAddress({
							fail: res => {
								that.setData({
									isAddress: true
								});
							}
						})
					}
				},
				fail: res => {
					util.showToast('保存失败', 'none')
				}
			})
		}
	},
	getNewHb() {
		wx.navigateTo({
			url: '../myRedPacket/myRedPacket',
		})
	},
	// 关闭地址弹窗
	popCancel: function() {
		this.setData({
			isAddress: false
		});
	},
	// 立即使用按钮事件
	useHb: function(userInfo) {
		let that = this;
		let list=[
			"_wMThdbbWFaOaYSuPgWsNv0nk2jgUNAm595LUomlQM8",
			"QBAvtzs4qJneH5taJC9dgSrOSqHtQSZQIgiGVuqoCb0",
			"3Hy6K-Jotl7XlDiTKg0M7aAEpwZxdiK9WR885q7Edo8"
		]
			wx.requestSubscribeMessage({
			  tmplIds: list,
			  success:(res)=>{
				  // let that = this
				if (!that.data.options.all) {
					that.JumpUrl(that.data.options.gid)
				}else if (that.data.is_get == 1) {
					util.showToast('授权成功~', 'none')
				}
				that.setData({
					Hb: false,
					red_id: ''
				})},
			  fail(res) {
				  // let that = this

				if (!that.data.options.all) {
					that.JumpUrl(that.data.options.gid)
				}else if (that.data.is_get == 1) {
					util.showToast('授权成功~', 'none')
				}
				that.setData({
					Hb: false,
					red_id: ''
				})},
			  complete:(err)=>{
				console.log('授权',err)
			  }
			})
		
		// util.showToast('领取成功~', 'none')
	},
	//跳转到详情页
	JumpUrl: function(gid) {
		wx.navigateTo({
			url: `../commodityDetail/commodityDetail?gid=${gid}&red_id=${this.data.options.red_id||''}`,
		})
		let data = ''
		if(this.data.red_packet){
			data = JSON.stringify(this.data.red_packet)
		}
		wx.setStorageSync('redData', data)
	},
	
	//跳转到详情页
	getCommodityDetail: function(e) {
		this.JumpUrl(e.currentTarget.dataset.id)

	},
	//下拉刷新
	onPullDownRefresh: function() {
		let that = this
		// that.getGoodList(1, that.data.tabArr.curHdIndex, that.data.red_id)
		wx.stopPullDownRefresh();
		api.goodsList({
			data: {
				page: 1,
				limit: 10,
				mid: 1,
				tag_id: Number(that.data.tabArr.curHdIndex)
			},
			success: res => {
				wx.stopPullDownRefresh();
				that.setData({
					bannerUrls: res.data.result.data.system_info.index_banner,
					goods_data: res.data.result.data.goods_data,
					page: 1,
					next: res.data.result.next,
					noMore: res.data.result.next === 0 ? true : false
				})
			}
		})
	},
	//触底加载下一页
	onReachBottom: function() {
		let that = this
		if (that.data.next != 0) {
			that.setData({
				getGoodsList: 0
			})
			let page = that.data.page + 1
			that.getGoodList(page, Number(that.data.tabArr.curHdIndex))
		} else {
			util.showToast('没有更多啦~', 'none')
		}

	},
	getOrder: function(e) {
		wx.navigateTo({
			url: `../myOrder/myOrder?index=${e.currentTarget.dataset.index +1}`,
		})
	},
	onShareAppMessage: function() {
		return {
			title: '禾霏彩妆',
			path: `pages/index/index`,
			success: function(res) {},
			fail: function(res) {
				// 转发失败
			}
		}
	},
	getExpect: function() {
		util.showToast('更多商品正在持续上架中,敬请期待~', 'none')
	},
	//倒计时
	countTime() {
		var that = this;
		that.setData({
			loadingtime: setInterval(function() {
				var date = new Date();
				var now = date.getTime();
				var endDate = (that.data.end_time).replace(/-/g, "/");
				endDate = new Date(endDate); //设置截止时间
				var end = endDate.getTime();
				var leftTime = end - now; //时间差                              
				var d, h, m, s, ms;
				h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
				m = Math.floor(leftTime / 1000 / 60 % 60);
				s = Math.floor(leftTime / 1000 % 60);
				ms = Math.floor(leftTime % 10);
				ms = ms < 100 ? ms : ms
				s = s < 10 ? "0" + s : s
				m = m < 10 ? "0" + m : m
				h = h < 10 ? "0" + h : h
				let time = {
					h: h,
					m: m,
					s: `${s}.${ms}`,
				}
				if (leftTime > 0) {
					that.setData({
						time: time
					})
				}
			}, 100)
		})
	},
	onHide: function() {
		clearInterval(this.data.loadingtime)
	},
	//前往投诉页面
	get_complain() {
		wx.navigateTo({
			url: '../complaint/complaint',
		})
	},
	//用户授权
	getUserProfile: function(e) {
		let This = this;
		console.log('触发了')
		wx.getUserProfile({
			desc: '用于展示用户个人信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				var app=getApp()
				app.globalData.wxshouquan=true
				if (res.errMsg == "getUserProfile:ok") { //授权成功
					//授权解密的信息
					console.log(res.userInfo);
					let params = {
						encryptedData: res.encryptedData,
						iv: res.iv,
						signature: res.signature,
						openid: This.data.userInfo.openid,
						code: This.data.userInfo.code,
						uname:res.userInfo.nickName
					};
					util.saveUserInfo(This, params).then(res => {
						if(!This.data.options.all){
							util.showToast('授权成功', 'none')
						}
						//使用es6的promise进行异步处理
						let promise = new Promise(function(resolve, reject) {
							util.getLogin(resolve)
						});
						promise.then(res => {
							This.getGoodList(1,1,'')
							setTimeout(()=>{
								if (This.data.red_id) {
									userInfo.red_id = This.data.red_id
									
									This.useHb(params)
								}
							},800)
						})
					}).catch(err => {
					    console.log(err)
					})
				} else { //取消授权
					utils.showToast('授权失败', 'none');
				}
			},
			complete:(err)=>{
				console.log('授权',err)
			}
		})
	},
//订阅消息
subScribe:function(res){
	let list=[
	"_wMThdbbWFaOaYSuPgWsNv0nk2jgUNAm595LUomlQM8",
	"QBAvtzs4qJneH5taJC9dgSrOSqHtQSZQIgiGVuqoCb0",
	"3Hy6K-Jotl7XlDiTKg0M7aAEpwZxdiK9WR885q7Edo8"
]
	wx.requestSubscribeMessage({
	  tmplIds: list,
	  success:(res)=>{},
	  fail(res) {},
	  complete:(err)=>{
		console.log('授权',err)
	  }
	})
}


})
